/*
 * Copyright (C) 2016 huanghaibin_dev <huanghaibin_dev@163.com>
 * WebSite https://github.com/MiracleTimes-Dev
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.elvis.library;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.utils.TextTool;
import ohos.app.Context;

import java.lang.reflect.Constructor;

final class YearViewAdapter extends BaseRecyclerAdapter<Month> {
    private CalendarViewDelegate mDelegate;
    private int mItemWidth, mItemHeight;

    YearViewAdapter(Context context) {
        super(context);
    }

    final void setup(CalendarViewDelegate delegate) {
        this.mDelegate = delegate;
    }


    final void setYearViewSize(int width, int height) {
        this.mItemWidth = width;
        this.mItemHeight = height;
        notifyDataChanged();
    }


    @Override
    ViewHolder onCreateDefaultViewHolder(ComponentContainer parent) {
        YearView yearView;
        if (TextTool.isNullOrEmpty(mDelegate.getYearViewClassPath())) {
            yearView = new DefaultYearView(mContext);
        } else {
            try {
                Constructor constructor = mDelegate.getYearViewClass().getConstructor(Context.class);
                yearView = (YearView) constructor.newInstance(mContext);
            } catch (Exception e) {
                yearView = new DefaultYearView(mContext);
            }
        }
        return new YearViewHolder(yearView, mDelegate);
    }

    @Override
    void onBindViewHolder(ViewHolder holder, Month item, int position) {
        YearViewHolder h = (YearViewHolder) holder;
        YearView view = h.mYearView;
        view.setLayoutConfig(new ComponentContainer.LayoutConfig(mItemWidth, mItemHeight));
        view.init(item.getYear(), item.getMonth());
        view.measureSize(mItemWidth, mItemHeight);
    }

    private static class YearViewHolder extends ViewHolder {

        YearView mYearView;

        YearViewHolder(Component itemView, CalendarViewDelegate delegate) {
            super(itemView);
            mYearView = (YearView) itemView;
            mYearView.setup(delegate);
        }
    }
}
